﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace DaZhong
{
    public class Util
    {

        /// <summary>
        /// 显示微信图片(解决防盗链问题)
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        public static string FormatImg(string html, string domain)
        {
            if (string.IsNullOrEmpty(html) || html.IndexOf(domain) == -1)
                return html;

            html = html.Replace("\r\n", "").Replace("\r", "").Replace("\n", "").Replace("\t", "");
            Regex res = new Regex("<img([\\s\\S].*?)>", RegexOptions.IgnoreCase);

            if (!res.IsMatch(html))
                return html;

            Regex reimg = new Regex("src=\"([\\s\\S].*?)\"", RegexOptions.IgnoreCase);
            MatchCollection list = res.Matches(html);
            MatchCollection lists = res.Matches(html);
            for (int i = 0; i < list.Count; i++)
            {
                if (list[i].Groups[1].Value.IndexOf(domain) == -1)
                    continue;
                try
                {
                    string src = reimg.Match(list[i].Groups[1].Value).Groups[1].Value;
                    html = html.Replace(lists[i].Value, string.Format("<script>showImg('{0}');</script>", reimg.Match(list[i].Groups[1].Value).Groups[1].Value));
                }
                catch (Exception ex) { }
            }
            return html;
        } 
    }
}
